package com.qsl.juc.producer_consumer;

import java.util.concurrent.locks.LockSupport;

/**
 * LockSupport 实现生产者与消费者
 * 这个具有局限性，可以试试 > 2 的线程数，写法和结果有什么问题
 *
 * @author 青石路
 * @date 2021/3/15 21:48
 */
public class LockSupportDemo {

    private static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        t1 = new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                shareData.increment(t2);
            }
        }, "t1");

        t2 = new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                shareData.decrement(t1);
            }
        }, "t2");

        t1.start();
        t2.start();

    }

    static class ShareData {

        // volatile 能不能去掉
        private volatile int num = 0;

        public void increment(Thread awake) {
            num++;
            System.out.println(Thread.currentThread().getName() + " " + num);
            LockSupport.unpark(awake);
            LockSupport.park();
        }

        public void decrement(Thread awake) {
            LockSupport.park();
            num--;
            System.out.println(Thread.currentThread().getName() + " " + num);
            LockSupport.unpark(awake);
        }
    }
}
